package com.reform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.reform.config.JwtTokenUtil;
import com.reform.mapper.TeacherMapper;
import com.reform.pojo.admin.Admin;
import com.reform.pojo.common.Dealt;
import com.reform.pojo.expert.ExpertLabel;
import com.reform.pojo.phase.ViewPhaseCheck;
import com.reform.pojo.teacher.Teacher;
import com.reform.pojo.teacher.TeacherInfo;
import com.reform.res.Result;
import com.reform.res.ResultCode;
import com.reform.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reform.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 教师表 服务实现类
 * </p>
 *
 * @author mortale
 * @since 2021-06-26
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements ITeacherService {

    @Autowired
    SchoolDBService schoolDBService;
    @Autowired
    IExpertService expertService;
    @Autowired
    IExpertLabelService expertLabelService;
    @Autowired
    IAdminService adminService;
    @Autowired
    IViewProjectService viewProjectService;
    @Autowired
    IViewPhaseCheckService viewPhaseCheckService;
    @Autowired
    IPhaseTimeService phaseTimeService;

    @Autowired
    TeacherMapper teacherMapper;
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Value("${jwt.expireTime}")
    Long expireTime;


    /**
     * 登录
     *
     * @param gh
     * @param password
     * @param type
     * @return
     */
    @Override
    public Result login(String gh, String password, Integer type) {
        //校验参数是否为空或者为”“
        if (!VerifycUtils.verifyNullOrEmptyUtils(gh, password, type)) {
            return Result.failure(ResultCode.PARAM_IS_MISSING);
        }
        //工号长度有误 或者 类型有误
        if (!VerifycUtils.verifyTypeValueOrGhLength(gh, type)) {
            return Result.failure(ResultCode.PARAM_IS_WRONG);
        }
        //校验人事处，该教师是否在职
        Map<String, String> teacherInfo = null;
        try {
            teacherInfo = schoolDBService.getTeacherInfoByGh(gh);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //人事处找不到该教师信息
        if (teacherInfo == null) {
            return Result.failure(ResultCode.USER_NOT_WORKING);
        }
        //判断是否专家
        if (type == 2) {
            if (!verifyExpertAuth(gh, type)) {
                return Result.failure(ResultCode.USER_AUTH_FAIL);
            }
        }
        //判断是否管理员
        if (type == 3) {
            if (!verifyAdminAuth(gh, type)) {
                return Result.failure(ResultCode.USER_AUTH_FAIL);
            }
        }
        Teacher teacher = teacherMapper.selectOne(new QueryWrapper<Teacher>().eq("gh", gh));
        //用户未注册
        if (teacherMapper.selectOne(new QueryWrapper<Teacher>().eq("gh", gh)) == null) {
            //输入密码与初始密码一致（暨输入密码为身份证号后六位）
            if (password.toLowerCase().equals(teacherInfo.get("sfzh").substring(12).toLowerCase())) {
                return Result.failure(ResultCode.USER_NOT_REGISTRIED);
            }
            //输入密码不为身份证后号六位
            else {
                return Result.failure(ResultCode.USER_ARGS_ERROR);
            }
        }
        if (!SHA256Encoder.getSHA256(password).equals(teacher.getPassword())) {
            return Result.failure(ResultCode.USER_ARGS_ERROR);
        }
        String uuid = UUIDUtils.getUUID();
        String token = jwtTokenUtil.generateToken(gh, teacherInfo.get("xm"), type, uuid);
        Map<String, String> tokenMap = new HashMap<String, String>();
        tokenMap.put("tokenHead", tokenHead);
        tokenMap.put("token", token);
        tokenMap.put("jsession_id", uuid);
        redisUtils.set(uuid, token, expireTime);
        return Result.success(ResultCode.SUCCESS, tokenMap);
    }

    /**
     * 初始化教师信息
     *
     * @param teacher
     * @return
     */
    @Override
    public Result init(Teacher teacher) throws SQLException {
        boolean verity = VerifycUtils.verifyNullOrEmptyUtils(teacher.getGh(), teacher.getEmail(), teacher.getPassword(), teacher.getType());
        if (!verity) {
            return Result.failure(ResultCode.PARAM_IS_MISSING);
        }
        boolean verity2 = VerifycUtils.verifyTypeValueOrGhLength(teacher.getGh(), teacher.getType());
        if (!verity2) {
            return Result.failure(ResultCode.PARAM_IS_WRONG);
        }
        if (teacherMapper.selectOne(new QueryWrapper<Teacher>().eq("gh", teacher.getGh())) != null) {
            return Result.failure(ResultCode.USER_HAS_REGISTRIED);
        }
        teacher.setPassword(SHA256Encoder.getSHA256(teacher.getPassword()));
        if (teacher.getType() == 2) {
            boolean charge = expertService.chargeExpertAuth(teacher.getGh());
            if (!charge) {
                return Result.failure(ResultCode.USER_AUTH_FAIL);
            }
        }
        if (teacher.getType() == 3) {
            boolean charge = adminService.chargeAdminAuth(teacher.getGh());
            if (!charge) {
                return Result.failure(ResultCode.USER_AUTH_FAIL);
            }
        }
        int insert = teacherMapper.insert(teacher);
        if (insert < 1) {
            return Result.failure(ResultCode.SYSTEM_INITIALIZE_ERROR);
        }
        Map<String, String> teacherInfo = schoolDBService.getTeacherInfoByGh(teacher.getGh());
        String uuid = UUIDUtils.getUUID();
        String token = jwtTokenUtil.generateToken(teacher.getGh(), teacherInfo.get("xm"), teacher.getType(), uuid);
        Map<String, String> tokenMap = new HashMap<String, String>();
        tokenMap.put("tokenHead", tokenHead);
        tokenMap.put("token", token);
        tokenMap.put("jsession_id", uuid);
        redisUtils.set(uuid, token, expireTime);
        return Result.success(ResultCode.SUCCESS, tokenMap);
    }

    /**
     * 获取当前用户默认信息
     *
     * @param request
     * @return
     * @throws SQLException
     */
    @Override
    public Result getDefaultTeacherInfo(HttpServletRequest request) throws SQLException {
        return Result.success(ResultCode.SUCCESS, schoolDBService.getTeacherInfoByGh(jwtTokenUtil.getGHFromToken(request.getHeader("token"))));
    }

    /**
     * 修改当前用户邮箱
     *
     * @param request
     * @return
     */
    @Override
    public Result changeEmail(String email, String password, String code, HttpServletRequest request) {
        if (redisUtils.get(email) == null || redisUtils.getExpire(email) < 0 || !((String) redisUtils.get(email)).toLowerCase().equals(code.toLowerCase())) {
            return Result.failure(ResultCode.PARAM_EMAILCODE_IS_WRONG);
        }
        Teacher teacher = getTeacherByRequest(request);
        boolean verifyPassword = verifyPassword(password, request);
        if (!verifyPassword) {
            return Result.failure(ResultCode.USER_PASSWORD_ERROR);
        }
        if (teacher.getEmail().equals(email)) {
            return Result.failure(ResultCode.USER_EMAIL_NOT_CHAHGED);
        }
        teacher.setEmail(email);
        int update = teacherMapper.update(teacher, new QueryWrapper<Teacher>().eq("gh", teacher.getGh()));
        if (update > 0) {
            return Result.success(ResultCode.SUCCESS);
        } else {
            return Result.failure(ResultCode.FAILURE);
        }
    }

    /**
     * 修改当前用户的密码
     *
     * @param request
     * @return
     */
    @Override
    public Result changePassword(String password, String newPassword, HttpServletRequest request) {
        boolean verifyPassword = verifyPassword(password, request);
        if (!verifyPassword) {
            return Result.failure(ResultCode.USER_PASSWORD_ERROR);
        }
        if (password.equals(newPassword)) {
            return Result.failure(ResultCode.USER_NEWPASSWORD_EQUALS_OLDPASSWORD);
        }
        // *** 此处是将新密码传入与旧密码比较，若相同为true
        if (verifyPassword(newPassword, request)) {
            return Result.failure(ResultCode.USER_NEWPASSWORD_EQUALS_OLDPASSWORD);
        }
        Teacher teacher = getTeacherByRequest(request);
        teacher.setPassword(SHA256Encoder.getSHA256(newPassword));
        int update = teacherMapper.update(teacher, new QueryWrapper<Teacher>().eq("gh", teacher.getGh()));
        if (update > 0) {
            return Result.success(ResultCode.SUCCESS);
        } else {
            return Result.failure(ResultCode.FAILURE);
        }
    }

    /**
     * 获取用户本地信息
     *
     * @param request
     * @return
     */
    @Override
    public Result getDefaultLocalTeacherInfo(HttpServletRequest request) {
        Teacher teacher = getTeacherByRequest(request);
        //设置密码不可见
        teacher.setPassword("********");
        return Result.success(ResultCode.SUCCESS, teacher);
    }

    /**
     * 用户找回密码
     *
     * @param gh
     * @param password
     * @return
     */
    @Override
    public Result findPassword(String gh, String email, String password) {
        Teacher teacher = teacherMapper.selectOne(new QueryWrapper<Teacher>().eq("gh", gh));
        //本地未注册
        if (teacher == null) {
            return Result.failure(ResultCode.USER_NOT_REGISTRIED);
        }
        //提交信息有误：前端验证未做到位
        boolean verify = VerifycUtils.verifyNullOrEmptyUtils(password, email);
        if (!verify) {
            return Result.failure(ResultCode.PARAM_IS_MISSING);
        }
        // 邮箱判定错误
        if (!teacher.getEmail().equals(email)) {
            return Result.failure(ResultCode.PARAM_EMAIL_IS_WRONG);
        }
        //新密码和原密码一致
        if (SHA256Encoder.getSHA256(password).equals(teacher.getPassword())) {
            return Result.success(ResultCode.SUCCESS);
        }
        // 设置密码
        teacher.setPassword(SHA256Encoder.getSHA256(password));
        //更新到数据库
        int update = teacherMapper.update(teacher, new QueryWrapper<Teacher>().eq("gh", gh));
        // 若不大于或等于一则证明验证失败
        if (update > 0) {
            return Result.success(ResultCode.SUCCESS);
        } else {
            return Result.failure(ResultCode.FAILURE);
        }
    }

    /**
     * 重置教师信息
     *
     * @param gh
     * @return
     */
    @Override
    public Result resetTeacher(String gh) {
        if (teacherMapper.selectOne(new QueryWrapper<Teacher>().eq("gh", gh)) == null) {
            return Result.success(ResultCode.SUCCESS);
        }
        int delete = teacherMapper.delete(new QueryWrapper<Teacher>().eq("gh", gh));
        if (delete > 0) {
            return Result.success(ResultCode.SUCCESS);
        } else {
            return Result.failure(ResultCode.FAILURE);
        }
    }

    @Override
    public Result getAllTeacherInfo() throws SQLException {
        List<TeacherInfo> teacherInfoList;
        teacherInfoList = (List<TeacherInfo>) redisUtils.get("teacherInfoList");
        if (!VerifycUtils.verifyNullOrEmptyUtils(teacherInfoList)) {
            teacherInfoList = schoolDBService.selectAll();
            redisUtils.set("teacherInfoList", teacherInfoList, 60 * 60 * 24);
        }
        return Result.success(ResultCode.SUCCESS, teacherInfoList);
    }

    @Override
    public String getTeacherNameByGh(String gh) throws SQLException {
        return schoolDBService.getTeacherXmByGh(gh);
    }

    @Override
    public String getTeacherDepByGh(String gh) throws SQLException {
        return schoolDBService.getTeacherDepByGh(gh);
    }

    /**
     * 根据请求取出用户信息
     *
     * @param request
     * @return
     */
    public Teacher getTeacherByRequest(HttpServletRequest request) {
        String token = request.getHeader("token");
        String gh = jwtTokenUtil.getGHFromToken(token);
        return teacherMapper.selectOne(new QueryWrapper<Teacher>().eq("gh", gh));
    }

    /**
     * 验证用户密码是否正确
     *
     * @param password
     * @param request
     * @return
     */
    public boolean verifyPassword(String password, HttpServletRequest request) {
        Teacher teacher = getTeacherByRequest(request);
        password = SHA256Encoder.getSHA256(password);
        if (!teacher.getPassword().equals(password)) {
            return false;
        }
        return true;
    }


    /**
     * 验证是否专家
     *
     * @param gh
     * @param type
     * @return
     */
    @Override
    public boolean verifyExpertAuth(String gh, Integer type) {
        return expertLabelService.list(new QueryWrapper<ExpertLabel>().eq("gh", gh)).size() != 0;
    }

    /**
     * 验证是否管理员
     *
     * @param gh
     * @param type
     * @return
     */
    @Override
    public boolean verifyAdminAuth(String gh, Integer type) {
        return adminService.getOne(new QueryWrapper<Admin>().eq("gh", gh)) != null;
    }

    @Override
    public Result getTeacherTypeByGH(String gh) {
        Map<String, Object> map = new HashMap<>();
        //设置默认编号，默认为-1，代表不是
        map.put("teacher_id", "1");
        map.put("expert_id", "-1");
        map.put("admin_id", "-1");
        //查询是否为管理员
        Admin admin = adminService.getOne(new QueryWrapper<Admin>().eq("gh", gh));
        if (admin != null) {
            map.put("admin_id", "3");
        }
        if (verifyExpertAuth(gh, 0)) {
            map.put("expert_id", "2");
        }
        return Result.success(ResultCode.SUCCESS, map);
    }

    @Override
    public Result getTeacherDealt(HttpServletRequest request) throws SQLException {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.failure(ResultCode.USER_AUTH_Login_LAPSE);
        }
        HashMap<String, Object> resMap = new HashMap<>();
        Integer type = jwtTokenUtil.getTypeFromToken(token);
        String gh = jwtTokenUtil.getGHFromToken(token);
        //教师导航权限为1
        if (type == 1) {
            List<Dealt> backList = viewProjectService.getTeacherDealt(gh);
            List<ViewPhaseCheck> phaseList = viewPhaseCheckService.list(new QueryWrapper<ViewPhaseCheck>().eq("pc_status", 0).eq("belong", gh).eq("type", 2));
            phaseList.addAll(viewPhaseCheckService.list(new QueryWrapper<ViewPhaseCheck>().eq("pc_status", -1).eq("belong", gh).eq("type", 2)));
            List<ViewPhaseCheck> closeList = viewPhaseCheckService.list(new QueryWrapper<ViewPhaseCheck>().eq("pc_status", 0).eq("belong", gh).eq("type", 3));
            closeList.addAll(viewPhaseCheckService.list(new QueryWrapper<ViewPhaseCheck>().eq("pc_status", -1).eq("belong", gh).eq("type", 3)));
            resMap.put("backList", backList);
            resMap.put("phaseList", phaseList);
            resMap.put("closeList", closeList);
            return Result.success(ResultCode.SUCCESS, resMap);
        }
        //专家导航权限为2
        if (type == 2) {
            //获取专家下的批次
            return Result.success(ResultCode.SUCCESS, phaseTimeService.getNeedDealt(gh, 2));
        }
        //管理员权限分为查询与操作管理员
        if (type == 3) {
            //基本院查询管理员为3
            Admin admin = adminService.getAdminByGh(gh);
            //查询管理员此处为0，操作管理员此处为1
            Integer adminType = admin.getType();
            Integer depId = admin.getDepId();
            //校查询管理员为5
            if (depId == 0) {
                return phaseTimeService.getNeedDealt(gh, 3);
            }
            if (depId != 0) {
                return phaseTimeService.getNeedDealt(gh, 4);
            }
            //暨权限分为 3（院查） 4（院操） 5（校查） 6（校操）
        }
        return Result.failure(ResultCode.FAILURE, resMap);
    }

    @Override
    public Result changeIdentity(HttpServletRequest request, Integer type) {

        String token = request.getHeader("token");
        if (token == null) {
            return Result.failure(ResultCode.USER_AUTH_Login_LAPSE);
        }
        String gh = jwtTokenUtil.getGHFromToken(token);
        String name = jwtTokenUtil.getNameFromToken(token);
        String oldUuid = jwtTokenUtil.getUUIDFromToken(token);
        //判断是否专家
        if (type == 2) {
            if (!verifyExpertAuth(gh, type)) {
                return Result.failure(ResultCode.USER_AUTH_FAIL);
            }
        }
        //判断是否管理员
        if (type == 3) {
            if (!verifyAdminAuth(gh, type)) {
                return Result.failure(ResultCode.USER_AUTH_FAIL);
            }
        }
        String resToken = jwtTokenUtil.generateToken(gh, name, type, oldUuid);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("tokenHead", tokenHead);
        tokenMap.put("token", resToken);
        tokenMap.put("jsession_id", oldUuid);
        redisUtils.set(oldUuid, resToken, expireTime);
        return Result.success(ResultCode.SUCCESS, tokenMap);
    }

    @Override
    public Result initAll() throws SQLException {
        List<String> allGH = schoolDBService.getAllGH();

        Teacher teacher = new Teacher();
        teacher.setPassword("515605c5558dda8c3044cc7d824a8eba271220d4fd8004e83701cabcc35e0d3b");
        teacher.setEmail("1847013421@qq.com");

        for (String s : allGH) {
            teacher.setGh(s);
            teacherMapper.insert(teacher);
        }
        return null;
    }


}
